import type { IUserLoginData } from "@/api/user";
import { UserLogin } from "@/api/user";
import { removeToken, setToken } from "@/utils/auth";
export const useUserStore = defineStore(
  "userStore",
  () => {
    const userState = reactive({
      token: ""
    });
    const login = async (userInfo: IUserLoginData) => {
      try {
        const { username, password } = userInfo;
        const response = await UserLogin({
          username: username.trim(),
          password
        });
        const { data } = response;
        userState.token = data.token;
        setToken(data.token);
        return Promise.resolve(response);
      } catch (e) {
        return Promise.reject(e);
      }
    };

    const LoginOut = () => {
      userState.token = "";
      removeToken();
    };

    return {
      userState,
      login,
      LoginOut
    };
  },
  {
    persist: {
      storage: localStorage,
      pick: ["userState.token"]
    }
  }
);
